package com.nstar.sinaweibo.components
{
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.controls.Text;
	import mx.events.FlexEvent;

	/**
	 * 动态文本显示
	 * 说明：模板键盘输入效果的动态文本显示
	 * 日期：2011.1.3
	 */ 
	public class AnimateText extends Text
	{
		public static const STOPPED:String = "stopped";
		
		private var timer:Timer;
		private var repeatTimer;
		private var index:int = 1;//text position
		private var delay:Number = 20;//repeat interval
		public var originalText:String;//keep the original text
		
		public var actived:Boolean = true;//激活开关
		
		
		public function AnimateText()
		{
			super();
			this.addEventListener(FlexEvent.CREATION_COMPLETE,init);
		}
		
		//保存原始的文本信息，并清空文本
		private function init(event:FlexEvent):void{
			if(actived){
				originalText = text;
				text = "";
			}
		}
		
		private function getTimer():Timer{
			if(!timer){
				timer = new Timer(delay);
				timer.addEventListener(TimerEvent.TIMER,timerHandler);
			}
			return timer;
		}
		
		
		//文本显示完后停止定时器
		private function timerHandler(event:TimerEvent):void{
			if(index>originalText.length){
				//delete the last "_"
				htmlText = originalText;
				stop();
				return;
			}
			var t:String = originalText.substr(0,index);
			htmlText = t+"_";//添加下划线光标效果
			index++;
		}
		
		//开始显示文本
		public function start(delay:Number=20):void{
			if(actived){
				this.delay = delay;
				text = "";
				repeatTimerHandler();
			}else{
				trace("animator not actived!");
			}
		}
		
		//停止定时器
		public function stop():void{
			trace("stoped!");
			timer.stop();
			index = 0;
			this.dispatchEvent(new Event(STOPPED));
		}
		
		//先显示一下文本输入前的光标闪烁效果
		private function repeatTimerHandler():void{
			repeatTimer = new Timer(200,6);//有限次数的定时器
			repeatTimer.addEventListener(TimerEvent.TIMER,repeatHandler);
			repeatTimer.addEventListener(TimerEvent.TIMER_COMPLETE,repeatHandler);
			repeatTimer.start();
		}
		
		//光标闪烁效果只显示几次就可以了，然后启动文本显示的定时器
		private function repeatHandler(event:TimerEvent):void{
			switch(event.type){
				case TimerEvent.TIMER:
					var s:String = "";
					text = text==""?"_":"";
					break;
				case TimerEvent.TIMER_COMPLETE:
					getTimer();
					timer.reset();
					timer.start();
					break;
			}
		}
	}
}